<?php

namespace app\client\controller\say;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\model\banxi\learn\LearnSayQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\say\SayTeachSentence as SayTeachSentenceModel;

class SayTeachSentence extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function listTeachSentence()
    {
        $params = $this->request->only(['index', 'limit', 'gradeId'], 'param');
        if (empty($params['gradeId'])) {
            $this->ok('ok', []);
        }

        $sayTeachSentenceModel = new SayTeachSentenceModel();
        $where = [
            ['gradeId', '=', $params['gradeId']],
            ['status', '=', 1],
            ['parentId', '=', 0]
        ];

        $pageParams = get_page_params($params);
        $studentId = $this->auth->getUserInfo()['id'];

        $list = $sayTeachSentenceModel
            ->where($where)
            ->order(['id' => 'asc', 'sortNum' => 'asc'])
            ->field('id,gradeId,sentenceGroupEn,sentenceGroupZh,name,courseExperience')
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ])
            ->each(function ($item) use ($sayTeachSentenceModel, $studentId) {
                // 如果是体验课，直接解锁
                if ($item['courseExperience']) {
                    $item['isLock'] = false;
                    return;
                }
                // 检查解锁条件
                $checkResult = $sayTeachSentenceModel->alias('a')
                    ->where('a.id', $item['id'])
                    ->where('a.parentId', 0)
                    ->where(function ($query) use ($studentId) {
                        $query->whereExists(function ($existsQuery) use ($studentId) {
                            $existsQuery->name('banxi_student_course')
                                ->whereRaw('courseId = a.id')
                                ->where('studentId', $studentId)
                                ->where('del', 0);
                        })->whereOr(function ($query) use ($studentId) {
                            $query->whereExists(function ($existsQuery) use ($studentId) {
                                $existsQuery->name('banxi_learn_say_question_record')
                                    ->whereRaw('sayTeachSentenceId = a.id')
                                    ->where('studentId', $studentId)
                                    ->where('learnMeans', LearnMeansEnum::E1)
                                    ->where('del', 0);
                            });
                        });
                    })->count();
                $item['isLock'] = $checkResult <= 0;
            });

        $this->ok('ok', result_row($list));
    }

    //母句详情
    public function getTeachSentenceInfo()
    {
        $id = $this->request->param('id');
        $trainerId = $this->request->param('trainerId');
        if (!$id) {
            $this->fail('缺少必要参数');
        }
        //查询上次是否有未完成
        $studentId = $this->auth->getUserInfo()['id'];
        $where = [
            'studentId' => $studentId,
            'learnMeans' => 2,
            'sayTeachSentenceId' => $id,
            'isSubmit' => 1
        ];
        if ($trainerId) {
            $where['trainerId'] = $trainerId;
            $where['learnMeans'] = 1;
        }
        $LearnSayQuestionRecord = new LearnSayQuestionRecord();
        $lastStudy = $LearnSayQuestionRecord->where($where)->order(['id' => 'desc'])->find();
        $lastFinish = false;//上次是否有未完成
        $lastStudyIds = [];//上次学过id
        $lastStudyUnGraspIds = [];//上次未掌握id
        $lastStudyGraspIds = [];//上次掌握id
        $lastStudyAnswerList = [];//上次选择题用户答案
        //设置上次的记录
        if ($lastStudy) {
            $learnSayQuestionAnswerRecord = new LearnSayQuestionAnswerRecord();
            $lastStudyList = $learnSayQuestionAnswerRecord->where([
                ['recordId', '=', $lastStudy['id']],
            ])->field('sayTeachSentenceId,answerCorrect,isCorrect')->select();
            foreach ($lastStudyList as $item) {
                if ($item['isCorrect'] == -1) {
                    $lastFinish = true;
                    break;
                }
            }
            if ($lastFinish) {
                foreach ($lastStudyList as $item) {
                    if ($item['isCorrect'] == -1) {
                        continue;
                    } else {
                        if ($item['isCorrect'] == 0) {
                            $lastStudyUnGraspIds[] = $item['sayTeachSentenceId'];
                        }
                        if ($item['isCorrect'] == 1) {
                            $lastStudyGraspIds[] = $item['sayTeachSentenceId'];
                        }
                        $lastStudyAnswerList[] = [
                            'id' => $item['sayTeachSentenceId'],
                            'isCorrect' => is_null($item['answerCorrect']) ? '' : $item['answerCorrect']
                        ];
                        $lastStudyIds[] = $item['sayTeachSentenceId'];
                    }
                }
            }
        }
        //句子和子句详情
        $sayTeachSentenceModel = new SayTeachSentenceModel();
        $list = $sayTeachSentenceModel->where(['id|parentId' => $id])->order([
            'parentId' => 'asc',
            'id' => 'asc',
            'sortNum' => 'asc'
        ])->select()->toArray();
        if (empty($list)) {
            $this->fail('母句数据不存在');
        }
        $parentSentence = [];
        foreach ($list as &$item) {
            if ($item['parentId'] == 0) {
                $parentSentence = $item;
                if (in_array($item['id'], $lastStudyIds)) {
                    $lastStudyIds = array_values(array_diff($lastStudyIds, [$item['id']]));
                }
            }
            $item['questionList'] = $sayTeachSentenceModel->splitQuestion($item['question'], $item['answer']);
            $item['imageOption'] = $sayTeachSentenceModel->getOtherSentenceImage($id, $item['sentenceImage']);
            $option = explode(',', $item['answer']);
            $item['optionInfo'] = $sayTeachSentenceModel->getOtherSentenceAnswer($id, $option);
        }
        unset($item);
        $info = [
            'parentSentence' => $parentSentence,
            'list' => $list,
            'lastStudyIds' => $lastStudyIds,
            'lastStudyUnGraspIds' => $lastStudyUnGraspIds,
            'lastStudyGraspIds' => $lastStudyGraspIds,
            'lastStudyAnswerList' => $lastStudyAnswerList,
            'lastFinish' => $lastFinish
        ];
        $this->ok('ok', $info);
    }

}